﻿using System;
using System.Linq;
using Soundteller.Audio.Repositories.Interfaces;
using Soundteller.AudioVisual.Model;
using Soundteller.AudioVisual.Repositories.Interfaces;
using Soundteller.AudioVisual.Services.Interfaces;
using Soundteller.Visual.Model;

namespace Soundteller.AudioVisual.Services
{
    public class PadToucher : IPadToucher
    {
        private readonly IPadRepository _padRepository;
        private readonly ISoundBufferRepository _soundBufferRepository;

        public PadToucher(IPadRepository padRepository, ISoundBufferRepository soundBufferRepository)
        {
            if (padRepository == null) throw new ArgumentNullException("padRepository");
            if (soundBufferRepository == null) throw new ArgumentNullException("soundBufferRepository");

            _padRepository = padRepository;
            _soundBufferRepository = soundBufferRepository;
        }

        public void Touch(PadTouchArguments arguments)
        {
            if (arguments == null) throw new ArgumentNullException("arguments");

            var touchedPads = _padRepository.GetByGraphicCategory(GraphicCategories.PAD)
                .Where(g => IntersectionCalculator.Intersects(arguments.X, arguments.Y, g.Graphic.X, g.Graphic.Y, g.Graphic.Width, g.Graphic.Height));

            if (!touchedPads.Any())
                return;

            foreach (var touchedPad in touchedPads)
            {
                _soundBufferRepository.Push(touchedPad.Sound);
            }
        }
    }
}
